/**
 * axios 二次封装
 */

import axios from 'axios'
import config from './../config'
import { ElMessage } from 'element-plus'
import router from './../router'

const TOKEN_INVALID = 'Token 验证失败，请重新登录'
const NETWORK_ERROR = '网络请求异常，请稍后重试'


// 创建 axios 实例对象
const service = axios.create({
    baseURL: config.baseApi,
    timeout: 8000
})

// 请求拦截
service.interceptors.request.use((req) =>{
    // TO-DO  JWT Token 补充
    const header = req.headers;
    if(!header.Authorization){
        header.Authorization = 'Bear Jack'
    }
    return req;
})


// 响应拦截
service.interceptors.response.use((res) =>{
   const { code,data,message } = res.data;
    if(code == 0){
        return data;
    }else if(code == 4001){
        ElMessage.error(TOKEN_INVALID)
        setTimeout(()=>{
            router.push('/login')
        },1500)
        return Promise.reject(TOKEN_INVALID)
    }else if(code == 9999){
        ElMessage.error(message)
        return Promise.reject(message)
    }else{
        ElMessage.error(msg || NETWORK_ERROR);
        return Promise.reject(msg || NETWORK_ERROR)
    }
})

/**
 * 请求核心参数
 * @param {*} options 请求配置
 * @returns 
 */
function request(options){

    options.method = options.method || 'get'
    if(options.method.toLowerCase === 'get'){
        options.params = options.data;
    }
    if(config.env === 'prod'){
        service.defaults.baseURL = config.baseApi;
    }else{
        service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
    }
    return service(options)
}

['get','post','put','delete','patch'].forEach((item) =>{
    request[item] = (url,data,options) =>{
        return request({
                url,
                data,
                method: item,
                ...options
            }
        )
    }
})

export default request;